<template>
  <div class="widget-form-container">
    <div v-if="data.list.length == 0" class="form-empty">从左侧拖拽组件</div>
    <el-form
      class="drag-form"
      label-suffix=":"
      :label-position="data.config.labelPosition"
      :label-width="data.config.labelWidth + 'px'"
      @click="clickDragForm"
    >
      <draggable
        class="preview"
        v-model="data.list"
        v-bind="{ group: 'people', ghostClass: 'ghost', animation: 200 }"
        @add="draggableAddEvent"
      >
        <template
          v-for="(element, index) in data.list"
          :key="element.type + (Math.random() * 1000 + 9999)"
        >
          <widget-form-item
            :class="[
              'widget-form-item',
              selectKey === data.list[index].key ? 'active' : '',
            ]"
            :element="element"
            :index="index"
            :data="data"
            @click.stop="handleWidgetSelect(index)"
          ></widget-form-item>
        </template>
      </draggable>
    </el-form>
  </div>
</template>
<script setup>
import { reactive, computed, ref } from "vue";
import { VueDraggableNext as draggable } from "vue-draggable-next";
import WidgetFormItem from "./WidgetFormItem.vue";
import { v4 as uuidV4 } from "uuid";
const props = defineProps({
  data: {
    type: Object,
    default: () => {},
  },
  select: {
    type: Object,
  },
});
const selectKey = ref("");
const selectWidget = computed(() => props.select);
const dragmove = () => {
  console.log("dragmove");
};
const draggableAddEvent = (evt) => {
  const newIndex = evt.newIndex;
  const key = uuidV4();
  props.data.list[newIndex] = {
    ...props.data.list[newIndex],
    key: props.data.list[newIndex].type + "_" + key,
  };
};
const emits = defineEmits(["update:select"]);
const handleWidgetSelect = (e) => {
  selectKey.value = props.data.list[e].key;
  emits("update:select", props.data.list[e]);
};
const clickDragForm = (e) => {
  selectKey.value = -1;
  emits("update:select", null);
};
</script>
<style lang="scss" scoped>
@import "../../style/index.scss";
.widget-form-container {
  margin: auto;
  height: 100%;
  .form-empty {
    position: absolute;
    text-align: center;
    width: 300px;
    font-size: 20px;
    top: 200px;
    left: 50%;
    margin-left: -150px;
    color: #ccc;
  }
  .drag-form {
    height: 100%;
    .preview {
      height: 100%;
      padding: 10px;
      box-sizing: border-box;
      .widget-form-item {
        &:hover {
          background: $primary-background-color;
          outline: 1px solid $primary-color;
          outline-offset: 0px;
        }
        &.active {
          outline: 2px solid $primary-color;
          border: 1px solid $primary-color;
          outline-offset: 0;
        }
      }
    }
  }
}
</style>
